package com.bosssoft.trainee.rbac.filter;

import com.bosssoft.trainee.rbac.entity.vo.FunVO;
import com.bosssoft.trainee.rbac.entity.vo.UsersVO;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebFilter(filterName = "Safe",urlPatterns = "/*")
public class Safe implements Filter {

    private static final String CSS = ".css";
    private static final String JS = ".js";
    private static final String GIT = ".gif";
    private static final String LOGIN = "login";
    private static final String USER_LOGIN = "userLogin";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;
        String uri = req.getRequestURI();
        //对静态资源做放行处理
        if(uri.endsWith(JS) || uri.endsWith(CSS)|| uri.endsWith(GIT)){
            chain.doFilter(req, res);
        }else{
            //对用户登录资源做放行
            if(uri.contains(LOGIN)  || uri.contains(USER_LOGIN)){
                chain.doFilter(req, res);
            }else{
                HttpSession session = req.getSession();
                UsersVO user = (UsersVO)session.getAttribute("user");
                List<FunVO> fun = user.getFun();
                //开关
                boolean flag = false;
                for(FunVO f: fun){
                    if(uri.contains(f.getFunUrl()) ){
                        flag = true;
                        break;
                    }
                }
                //根据开关的值来进行跳转
                if(flag){
                    chain.doFilter(req, res);
                }else{
                    res.sendRedirect("roleError");
                }
            }
        }
    }

    @Override
    public void destroy() {

    }
}
